package com.zang.blogz.listener;

import cn.dev33.satoken.listener.SaTokenListener;
import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.UpdateChainWrapper;
import com.zang.blogz.entity.UserAuth;
import com.zang.blogz.service.UserAuthService;
import io.github.vampireachao.stream.core.optional.Opp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * 自定义监听器
 *
 * @author 臧臧 on 2022/6/20
 */
@Component
public class MySaTokenListener implements SaTokenListener {

    @Autowired
    private UserAuthService userAuthService;

    @Override
    public void doLogin(String s, Object o, String s1, SaLoginModel saLoginModel) {

        Map<String, Object> extraData = saLoginModel.extraData;

        Integer id = (Integer) extraData.get("id");

        UpdateWrapper<UserAuth> queryWrapper = new UpdateWrapper<>();
        queryWrapper.lambda()
                .set(UserAuth::getLastLoginTime, new DateTime())
                .set(UserAuth::getIpSource, String.valueOf(extraData.get("ipSource")) )
                .set(UserAuth::getIpAddress, String.valueOf(extraData.get("ipAddress")))
                .eq(UserAuth::getUserInfoId, id);

        userAuthService.update(queryWrapper);
    }

    @Override
    public void doLogout(String s, Object o, String s1) {


    }

    @Override
    public void doKickout(String s, Object o, String s1) {

    }

    @Override
    public void doReplaced(String s, Object o, String s1) {

    }

    @Override
    public void doDisable(String s, Object o, long l) {

    }

    @Override
    public void doUntieDisable(String s, Object o) {

    }

    @Override
    public void doCreateSession(String s) {

    }

    @Override
    public void doLogoutSession(String s) {

    }
}